package com.xja.controller;

import com.xja.model.vo.resp.Result;
import com.xja.utils.AliOssUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author 蔡建国
 */
@RestController
@RequestMapping("/admin/common")
@Slf4j
@Tag(name = "通用模块")
@RequiredArgsConstructor
public class AdminCommonController {

    private final AliOssUtil aliOssUtil;

    @Operation(summary = "图片上传到阿里云oss")
    @PostMapping("/img/upload")
    public Result<String> upload(MultipartFile file) throws IOException {

        log.info("文件上传: {}", file);

        // 拿到文件的原始名
        String originalFilename = file.getOriginalFilename();
        // 拿到后缀名
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 制作唯一的文件名
        String objectName = UUID.randomUUID() + extName;

        // 上传文件并返回url
        String url = aliOssUtil.upload(file.getBytes(), objectName);

        // 返回图片url
        return Result.success(url);
    }
}
